package sunwul.mall.business.manager.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sunwul.mall.business.manager.entity.SysMenu;
import sunwul.mall.business.manager.mapper.SysMenuMapper;
import sunwul.mall.business.manager.service.SysMenuService;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 菜单管理服务接口实现
 *
 * @author sunwul
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2024-12-30 15:19:01
 */
@Slf4j
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 根据用户标识查询菜单权限集合
     */
    @Override
    public Set<SysMenu> queryUserMenuListByUserId(Long userId) {
        Set<SysMenu> sysMenus = sysMenuMapper.selectUserMenuListByUserId(userId);
        // 转为树形结构
        return transformTree(sysMenus, 0L);
    }

    /**
     * 将菜单权限集合转为树结构
     */
    private Set<SysMenu> transformTree(Set<SysMenu> sysMenus, Long pid) {
        // 根节点
        Set<SysMenu> roots = sysMenus.stream()
                .filter(sysMenu -> sysMenu.getParentId().equals(pid))
                .collect(Collectors.toSet());
//        roots.forEach(root -> {
//            // 过滤父节点值与当前根节点id一致的菜单集合
//            Set<SysMenu> child = sysMenus.stream()
//                    .filter(sysMenu -> sysMenu.getParentId().equals(root.getMenuId()))
//                    .collect(Collectors.toSet());
//            root.setChilds(child);
//        });
        // 递归获取
        roots.forEach(root -> root.setChilds(transformTree(sysMenus, root.getMenuId())));
        return roots;
    }
}